import { http } from '@/utils/request'
import type { ApiResponse, PageResult } from './types/common'

// ==================== 类型定义 ====================

/**
 * 帖子类型枚举
 */
export enum PostType {
  NORMAL = 'normal',    // 普通帖子
  WORK = 'work'         // 作品帖子
}

/**
 * 帖子响应VO
 */
export interface PostRespVO {
  id: number
  userId: number
  userNickname: string
  userAvatar: string
  type: PostType
  title?: string
  content: string
  images: string[]
  workId?: number        // 作品ID（绘本或绘本集ID）
  workType?: 'book' | 'bookset'  // 作品类型
  workTitle?: string     // 作品标题
  workCover?: string     // 作品封面
  likeCount: number
  commentCount: number
  isLiked: boolean       // 当前用户是否已点赞
  createTime: string
  updateTime: string
}

/**
 * 创建帖子请求VO
 */
export interface PostCreateReqVO {
  type: PostType
  title?: string
  content?: string // 允许为空，可以只发图片
  images?: string[]
  workId?: number
  workType?: 'book' | 'bookset'
}

/**
 * 更新帖子请求VO
 */
export interface PostUpdateReqVO {
  id: number
  title?: string
  content: string
  images?: string[]
}

/**
 * 帖子分页查询参数
 */
export interface PostPageParams {
  pageNo?: number
  pageSize?: number
  type?: PostType
  userId?: number
  keyword?: string
}

/**
 * 评论响应VO
 */
export interface CommentRespVO {
  id: number
  postId: number
  userId: number
  userNickname: string
  userAvatar: string
  content: string
  likeCount: number
  isLiked: boolean
  createTime: string
}

/**
 * 创建评论请求VO
 */
export interface CommentCreateReqVO {
  postId: number
  content: string
}

// ==================== API接口 ====================

/**
 * 获取社区信息流（分页）
 */
export function getCommunityPosts(params: PostPageParams = {}) {
  const defaultParams = {
    pageNo: 1,
    pageSize: 20,
    ...params
  }
  return http.get<ApiResponse<PageResult<PostRespVO>>>('/reading/community/posts/page', defaultParams)
}

/**
 * 获取帖子详情
 */
export function getPostDetail(id: number) {
  return http.get<PostRespVO>(`/reading/community/posts/get?id=${id}`)
}

/**
 * 创建帖子
 */
export function createPost(data: PostCreateReqVO) {
  return http.post<ApiResponse<number>>('/reading/community/posts/create', data)
}

/**
 * 更新帖子
 */
export function updatePost(data: PostUpdateReqVO) {
  return http.put<ApiResponse<void>>('/reading/community/posts/update', data)
}

/**
 * 删除帖子
 */
export function deletePost(id: number) {
  return http.delete<ApiResponse<void>>(`/reading/community/posts/delete?id=${id}`)
}

/**
 * 点赞/取消点赞帖子
 */
export function togglePostLike(postId: number) {
  return http.post<{
    isLiked: boolean
    likeCount: number
  }>(`/reading/community/posts/${postId}/like`)
}

/**
 * 获取帖子评论列表
 */
export function getPostComments(postId: number, params: { pageNo?: number; pageSize?: number } = {}) {
  const defaultParams = {
    pageNo: 1,
    pageSize: 20,
    ...params
  }
  return http.get<PageResult<CommentRespVO>>(`/reading/community/comments/page?postId=${postId}`, defaultParams)
}

/**
 * 创建评论
 */
export function createComment(data: CommentCreateReqVO) {
  return http.post<ApiResponse<number>>('/reading/community/comments/create', data)
}

/**
 * 删除评论
 */
export function deleteComment(id: number) {
  return http.delete<ApiResponse<void>>(`/reading/community/comments/delete?id=${id}`)
}

/**
 * 点赞/取消点赞评论
 */
export function toggleCommentLike(commentId: number) {
  return http.post<{
    isLiked: boolean
    likeCount: number
  }>(`/reading/community/comments/${commentId}/like`)
}

/**
 * 上传帖子图片
 */
export function uploadPostImage(file: File) {
  const formData = new FormData()
  formData.append('file', file)
  return http.post<ApiResponse<string>>('/reading/community/upload/image', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 举报帖子
 */
export function reportPost(postId: number, reason: string) {
  return http.post<ApiResponse<void>>('/reading/community/security/report', {
    postId,
    reason,
    type: 'post'
  })
}

/**
 * 举报评论
 */
export function reportComment(commentId: number, reason: string) {
  return http.post<ApiResponse<void>>('/reading/community/security/report', {
    commentId,
    reason,
    type: 'comment'
  })
}

/**
 * 敏感词检测
 */
export function checkSensitiveWords(content: string) {
  return http.post<ApiResponse<{
    hasSensitive: boolean
    sensitiveWords: string[]
    filteredContent: string
  }>>('/reading/community/security/sensitive-check', { content })
}

/**
 * 检查发帖频控
 */
export function checkPostLimit() {
  return http.get<ApiResponse<{
    canOperate: boolean
    remainingCount: number
    resetTime: string
    message?: string
  }>>('/reading/community/security/post-limit-check')
}

/**
 * 重置发帖频控（仅测试用）
 */
export function resetPostLimit() {
  return http.post<ApiResponse<boolean>>('/reading/community/security/reset-post-limit')
}



/**
 * 保存草稿
 */
export function saveDraft(content: string, images: string[]) {
  return http.post<ApiResponse<void>>('/reading/community/drafts/save', {
    content,
    images,
    type: 'post'
  })
}

/**
 * 获取草稿
 */
export function getDraft() {
  return http.get<ApiResponse<{
    content: string
    images: string[]
    createTime: string
  }>>('/reading/community/drafts/latest?type=post')
}

/**
 * 删除草稿（逻辑删除）
 */
export function deleteDraft() {
  return http.delete<ApiResponse<void>>('/reading/community/drafts/delete?type=post')
}

/**
 * 物理删除草稿
 * 用于发布动态后彻底删除草稿数据
 */
export function physicalDeleteDraft() {
  return http.delete<ApiResponse<void>>('/reading/community/drafts/physical-delete?type=post')
}

/**
 * 检查作品权限
 */
export function checkWorkPermission(workId: number, workType: 'book' | 'bookset') {
  return http.get<ApiResponse<{
    permission: 'allow' | 'preview' | 'deny'
    message: string
    previewPages?: number
  }>>(`/reading/community/work-permission/${workId}`, { workType })
}

/**
 * 获取作品详情（用于社区展示）
 */
export function getWorkDetail(workId: number, workType: 'book' | 'bookset') {
  return http.get<ApiResponse<{
    id: number
    title: string
    author: string
    cover: string
    description: string
    type: 'book' | 'bookset'
    totalPages: number
    permission: 'allow' | 'preview' | 'deny'
    isCollected: boolean
    readCount: number
    collectCount: number
    likeCount: number
  }>>(`/reading/community/works/${workId}`, { workType })
}

/**
 * 收藏/取消收藏作品
 */
export function toggleWorkCollect(workId: number, workType: 'book' | 'bookset') {
  return http.post<ApiResponse<{
    isCollected: boolean
    collectCount: number
  }>>(`/reading/community/works/${workId}/collect`, { workType })
}

/**
 * 检查评论频控
 */
export function checkCommentLimit() {
  return http.get<ApiResponse<{
    canComment: boolean
    remainingCount: number
    resetTime: string
  }>>('/reading/community/security/comment-limit-check')
}

/**
 * 批量检查敏感词
 */
export function batchCheckSensitiveWords(contents: string[]) {
  return http.post<ApiResponse<{
    results: Array<{
      content: string
      hasSensitive: boolean
      sensitiveWords: string[]
      filteredContent: string
    }>
  }>>('/reading/community/security/sensitive-check/batch', { contents })
}
